//
//  AppDelegate.m
//  IpadR
//
//  Created by edianzu on 2017/5/23.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "MainViewController.h"
#import "RealReachability.h"
#import "ReloadDataViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //创建新孩子ID
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    if ([user objectForKey:@"newChildId"] ==nil) {
        [user setObject:@-1000 forKey:@"newChildId"];
    }
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor clearColor];
   
    //网络状态
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        [manager startMonitoring];
        [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                {
                    // 位置网络
//                    [self pressLogin];
                    NSLog(@"位置网络");
                }
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                {
                    // 无法联网
                    NSLog(@"无法联网");
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                {
                    // WIFI
                    NSLog(@"当前使用的是WIFI网络");
//                    [self pressLogin];
                }
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
                {
                    // 手机自带网络
//                    [self pressLogin];
                    NSLog(@"当前在2g/3g/4g网络下");
                }
            }
        }];
    
    NSString* newStates = [self getNetWorkStates];
    NSLog(@"%@",newStates);
    if ([newStates isEqualToString:@"无网络"]) {
        if ([user objectForKey:@"AllData"] == nil  ) {
            NSLog(@"aaaaaaa");
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:[[NSClassFromString(@"LoginViewController")alloc]init]];
            self.window.rootViewController = navi;
        }else{
            NSLog(@"bbbbbbb");
            ReloadDataViewController * rlt = [[ReloadDataViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:rlt];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            self.window.rootViewController = navi;
        }

    }else{
        if ([user objectForKey:@"SchoolId"] == nil) {
            NSLog(@"sssssssssss%@",[user objectForKey:@"SchoolId"]);
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:[[NSClassFromString(@"LoginViewController")alloc]init]];
            self.window.rootViewController = navi;
        }else{
            [self pressLogin];
            ReloadDataViewController * rlt = [[ReloadDataViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:rlt];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            self.window.rootViewController = navi;
            //自动登录
            
        }
    }

    [self.window makeKeyAndVisible];
    //    [userDefault removeObjectForKey:@"Username"];
//    _userName = [userDefault objectForKey:@"Username"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:@"UIApplicationDidEnterBackgroundNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comeHome:) name:@"UIApplicationDidEnterBackgroundNotification" object:nil];

    
    return YES;
}

//只用系统的终止方法，实测不行。必须加入监听自定义方法。判断APP 停止，移除登录标记islogin
- (void)comeHome:(UIApplication *)application {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //移除UserDefaults中存储的用户信息
    [userDefaults removeObjectForKey:@"isLogin"];
    
    NSLog(@"进入后台");
}

#pragma mark  登陆
-(void)pressLogin{
    NSLog(@"开始登陆");
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSLog(@"LLLLLLLLLLLLLL%@",[user objectForKey:@"isLogin"]);
    if (![[user objectForKey:@"isLogin"] isEqualToString:@"isLogin"]) {
    NSString * urls = @"/authenticate/credentials";
    NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
    NSLog(@"%@,,,,%@",[user objectForKey:@"UserName"],[user objectForKey:@"PassWord"]);
    NSDictionary *parama = @{@"Username":[user objectForKey:@"UserName"],@"Password":[user objectForKey:@"PassWord"]};
    [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
        NSLog(@"登陆成功");
        NSString * isLogin = @"isLogin";
        [user setObject:isLogin forKey:@"isLogin"];
        //        NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        //        NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
//        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSDictionary * dic = dict[@"Meta"];
//        NSString * companyName = dict[@"DisplayName"];
//        NSLog(@"%@",companyName);
        }

     failure:^(NSError *error) {
        NSError * err = error;
        NSLog(@"登陆因为这个失败了%@",err.description);
      
        
    }];
    }
}

- (NSString *)getNetWorkStates{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
    NSString *state = [[NSString alloc]init];
    int netType = 0;
    //获取到网络返回码
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            
            switch (netType) {
                case 0:
                    state = @"无网络";
                    //无网模式
                    break;
                case 1:
                    state =  @"2G";
                    break;
                case 2:
                    state =  @"3G";
                    break;
                case 3:
                    state =   @"4G";
                    break;
                case 5:
                {
                    state =  @"wifi";
                    break;
                default:
                    break;
                }
            }
        }
        //根据状态选择
    }
    return state;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //移除UserDefaults中存储的用户信息
    [userDefaults removeObjectForKey:@"isLogin"];
}


@end
